<script>
import { each } from "svelte/internal";
import Progress from './Progress.svelte';
// https://github.com/NateScarlet/holiday-cn
let holidays = [
	{
		"name": "元旦",
		"date": "2022-01-01",
		"isOffDay": true
	},
	{
		"name": "清明节",
		"date": "2022-04-03",
		"isOffDay": true
	},
	{
		"name": "劳动节",
		"date": "2022-04-30",
		"isOffDay": true
	},
	{
		"name": "端午节",
		"date": "2022-06-03",
		"isOffDay": true
	},
	{
		"name": "中秋节",
		"date": "2022-09-10",
		"isOffDay": true
	},
	{
		"name": "国庆节",
		"date": "2022-10-01",
		"isOffDay": true
	}
];
import { onMount } from 'svelte';
let NowTime = new Date();
function getdata(year){
	fetch(`https://cdn.jsdelivr.net/gh/NateScarlet/holiday-cn@master/${year}.json`)
	.then(response => response.json())
	.then(json => {
		holidays = [];
		let days = json.days;
		const groupByName = days.reduce((group, day) => {
			const { name } = day;
			group[name] = group[name] ?? [];
			if(day.isOffDay&&group[name].length<1){
				group[name].offDay = 1;
				group[name].push(day);
			}else if(day.isOffDay){
				group[name].offDay++
			}
			return group;
		}, {});
		// console.log('groupByName',groupByName);
		Object.keys(groupByName).forEach(item => {
			// console.log('groupByName item',groupByName[item][0]);
			let day = Object.assign(groupByName[item][0],{offDay:groupByName[item].offDay})
			holidays.push(day)
		});
		// console.log('holidays',holidays);
		// console.log('holidays[holidays.length]',holidays[holidays.length-1]);
		if(holidays.length>0){
			let hasHoliday = getDistanceSpecifiedTime(holidays[holidays.length-1].date,NowTime);
			// console.log('111',hasHoliday);
			if(!hasHoliday){
				getdata(year+1);
			}
		}
		
		// console.log(json.days)
	})
	.catch(err => console.log('Request Failed', err)); 

}
onMount(async() => {
	let year = new Date().getFullYear();
	getdata(year);

	// console.log('res',res);
	setInterval( () => {
		NowTime = new Date()//修改数据让他可以实时更新
	}, 1000);
});
	/**
  * 获取距离指定时间还有多少天
  * @param {String | Number | Date} dateTime 日期时间
  * @example
  * ```javascript
  *     getDistanceSpecifiedTime('2019/02/02 02:02:00');
  *     getDistanceSpecifiedTime(1549036800000);
  *     getDistanceSpecifiedTime(new Date("2019/2/2 00:00:00"));
  * ```
  */
function getDistanceSpecifiedTime(dateTime,NowTime) {
    // 指定日期和时间
    var EndTime = new Date(dateTime);
    // 当前系统时间
    // var NowTime = new Date();
	if(NowTime>EndTime){return false}
    var t = EndTime.getTime() - NowTime.getTime();
    var d = Math.floor(t / 1000 / 60 / 60 / 24);
    var h = Math.floor(t / 1000 / 60 / 60 % 24);
    var m = Math.floor(t / 1000 / 60 % 60);
    var s = Math.floor(t / 1000 % 60);
    var html = d + " 天" + h + " 时" + m + " 分" + `00${s}`.slice(-2) + " 秒";
	return html
}
//获取前所在周的周六、周日
function getWeekDay() {
 let _date = new Date();
 let _nowTime = _date.getTime();
 let _week = _date.getDay();
 let _dayLongTime = 24 * 60 * 60 * 1000;
 let _furtureSundayTimes = _nowTime + (7 - _week) * _dayLongTime;
 let _furtureSaturdayTimes = _nowTime + (6 - _week) * _dayLongTime;
 _furtureSundayTimes = new Date(_furtureSundayTimes);
 _furtureSaturdayTimes = new Date(_furtureSaturdayTimes);
 // staurday
 let _satYear = _furtureSaturdayTimes.getFullYear();
 let _satMonth = _furtureSaturdayTimes.getMonth() + 1;
 let _satDay = _furtureSaturdayTimes.getDate();
 //sunday
 let _sunYear = _furtureSundayTimes.getFullYear();
 let _sunMonth = _furtureSundayTimes.getMonth() + 1;
 let _sunDay = _furtureSundayTimes.getDate();
 _satMonth = _satMonth >= 10 ? _satMonth : '0' + _satMonth;
 _satDay = _satDay >= 10 ? _satDay : '0' + _satDay;
 _sunMonth = _sunMonth >= 10 ? _sunMonth : '0' + _sunMonth;
 _sunDay = _sunDay >= 10 ? _sunDay : '0' + _sunDay;
 let _mealSaturDay = _satYear+'-'+_satMonth+'-'+_satDay;
 let _mealSunDay = _sunYear+ '-'+_sunMonth+'-'+_sunDay;
 let _weekendDay = [{
  saturDay: _mealSunDay
 }, {
  sunDay: _mealSaturDay
 }]
 return _mealSaturDay
//  return _weekendDay;
}

let thisWeekSaturDay = getWeekDay();
let week = new Date().getDay();

function showMsgNotification(title, msg) {
	var Notification = window.Notification || window.mozNotification || window.webkitNotification;
	if(Notification) {//支持桌面通知
		if(Notification.permission == "granted") {//已经允许通知
			var instance = new Notification(title, {
				body: msg,
				// icon: "images/reload.png",
			});
			instance.onclick = function() {
				console.log('onclick');
				instance.close();
			};
			instance.onerror = function() {
				console.log('onerror');
			};
			instance.onshow = function() {
				console.log('onshow');
			};
			instance.onclose = function() {
				console.log('onclose');
			};
		}else {//第一次询问或已经禁止通知(如果用户之前已经禁止显示通知，那么浏览器不会再次询问用户的意见，Notification.requestPermission()方法无效)
			alert('允许网站通知，每个小时提醒你喝水！')
			Notification.requestPermission(function(status) {
				if (status === "granted") {//用户允许
					var instance = new Notification(title, {
						body: msg,
						// icon: "images/reload.png"
					});
					instance.onclick = function() {
						// Something to do
					};
					instance.onerror = function() {
						// Something to do
					};
					instance.onshow = function() {
						// Something to do
					};
					instance.onclose = function() {
						// Something to do
					};
				}else {//用户禁止
					return false
				}
			});
		}
	}else {//不支持(IE等)
		alert("您的浏览器不支持桌面通知，请更换浏览器");
	}
};
var theTime =setInterval(function () {
	let NowTime = new Date();
	// console.log('NowTime.getSeconds()',NowTime.getSeconds());
	if (NowTime.getMinutes()==0&&NowTime.getSeconds()==0){   //myDate.getHours();    //获取当前小时数(0-23) 
		console.log('当前是',new Date().getMinutes())
		showMsgNotification('喝水提醒','每个小时都要喝水哦！')
		// clearInterval(theTime)
	} else{
		// console.log('时间未到')
	}
},1000,theTime)

let offWorkTime = new Date(); offWorkTime.setHours(18,0,0,0);

</script>

<main>
	{#if week!=0&&week!=6}
		<div class="week-satuday">距离星期六还有 {getDistanceSpecifiedTime(thisWeekSaturDay,NowTime)}</div>
		{#if new Date().getHours()>=9&&new Date().getHours()<18}
			<div>距离下班还有 {getDistanceSpecifiedTime(offWorkTime,NowTime)}</div>
			<Progress />
		{/if}
	{/if}
	{#each holidays as holiday}
		{#if getDistanceSpecifiedTime(holiday.date,NowTime)}
			<div class="item">
				<p class="holiday-name">{holiday.name}({holiday.offDay}天)</p>
				<div class="day">{holiday.date}</div>
				<p>{getDistanceSpecifiedTime(holiday.date,NowTime)}</p>
				
				<!-- <p>{holiday.isOffDay ? '休息日' : '工作日'}</p> -->
			</div>
		{/if}
	{/each}
	{#if holidays.length<1}
		<div class="no-holiday">今年的假期已经全部过去,期待明年的到来!</div>
	{/if}
	<div class="tip">[友情提示] 三甲医院 ICU 躺一天平均费用大概一万块。你晚一天进 ICU，就等于为你的家庭多赚一万块。少上班，多摸鱼。</div>
</main>

<style>
	main {
		text-align: center;
		margin: 5vh auto 0;
		line-height: 1.5;
		max-width: 700px;
	}
	.week-satuday{
		color: #00849B;
		margin-bottom: 10px;
	}
	.tip{
		color: #adadad;
		font-size: 12px;
		margin-top: 1em;
	}
	.no-holiday{
		font-size: 18px;
		margin-bottom: 24px;
	}
	.holiday-name {
		font-size: 1.2rem;
	}
	p {
		color: #003159;
	}
	.item{
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #00597E;
		margin-bottom: 24px;
		border-radius: 0.5rem;
		padding: 0 1em;
		box-shadow:5px 5px 3px rgba(53, 191, 189, 0.1);
		background: linear-gradient(105.23deg, #01A4FF 33.35%, #01FFC2 115.77%);
	}
	.item .day{color: rgba(255, 255, 255, .3);font-size: 2em;}
	@media (max-width: 640px) {
		.item .day{font-size: 1rem;}
	}
	
</style>